# -*- coding: utf-8 -*-
# =============================================================================
#     FileName:
#         Desc:
#       Author:
#        Email:
#     HomePage:
#      Version:
#   LastChange:
#      History:
# =============================================================================
import os.path
import sys
import argparse
import logging
from utils.logger_helper import LoggerHelper
from utils.redis_parser import MySQLParser
from utils.mysql_server import MySQLServer

from utils.common_config import CommonConfig

logger = logging.getLogger(name=CommonConfig.app_name)


class CommandParser(object):

    @classmethod
    def get_parser(cls):
        parser = argparse.ArgumentParser(
            description='解析RDB文件并导入到MySQL中',
            add_help=False)
        connect_setting = parser.add_argument_group('参数信息')
        parser.add_argument(
            '--help',
            dest='help',
            action='store_true',
            help='获取帮助信息',
            default=False
        )
        connect_setting.add_argument(
            '--rdb_file_path',
            dest='rdb_file_path',
            type=str,
            default="",
            help='RDB文件地址,无默认值'
        )
        connect_setting.add_argument(
            '--mysql_host',
            dest='mysql_host',
            type=str,
            default="127.0.0.1",
            help='数据库地址,默认值为127.0.0.1'
        )
        connect_setting.add_argument(
            '--mysql_port',
            dest='mysql_port',
            type=int,
            default=3306,
            help='数据库端口,默认值为3306'
        )
        connect_setting.add_argument(
            '--mysql_user',
            dest='mysql_user',
            type=str,
            default="root",
            help="数据库账号,默认值为root"
        )
        connect_setting.add_argument(
            '--mysql_password',
            dest='mysql_password',
            type=str,
            default="root",
            help="数据库密码,默认值为root"
        )
        connect_setting.add_argument(
            '--mysql_charset',
            dest='mysql_charset',
            type=str,
            default="utf8mb4",
            help="数据字符集,默认utf8mb4"
        )
        connect_setting.add_argument(
            '--connect_timeout',
            dest='connect_timeout',
            type=int,
            default=3,
            help="连接超时时间(单位秒),默认值为3秒"
        )
        connect_setting.add_argument(
            '--database_name',
            dest='database_name',
            type=str,
            default="redis_info",
            help="数据库名称,默认redis_info"
        )
        connect_setting.add_argument(
            '--table_name',
            dest='table_name',
            type=str,
            default="redis_info",
            help="数据表名称,默认redis_info"
        )
        connect_setting.add_argument(
            '--mysql_batch_insert_rows',
            dest='mysql_batch_insert_rows',
            type=int,
            default=1000,
            help="每批次插入记录数量(单位行),默认值1000"
        )
        connect_setting.add_argument(
            '--mysql_batch_sleep_seconds',
            dest='mysql_batch_sleep_seconds',
            type=float,
            default=0.1,
            help="每批次完成后休眠时间(单位秒),默认值0.1秒"
        )
        connect_setting.add_argument(
            '--min_key_length',
            dest='min_key_length',
            type=float,
            default=1000,
            help="最小key大小(单位Byte),默认值1000"
        )
        return parser

    @classmethod
    def parse_args(cls, command_args):
        need_print_help = False if command_args else True
        parser = cls.get_parser()
        args = parser.parse_args(command_args)

        if args.help or need_print_help:
            parser.print_help()
            sys.exit(1)
        if not os.path.exists(args.rdb_file_path):
            logger.warning("RDB文件({}}不存在,请检查.".format(args.rdb_file_path))
            sys.exit(1)
        mysql_server = MySQLServer(
            mysql_host=args.mysql_host,
            mysql_user=args.mysql_user,
            mysql_password=args.mysql_password,
            mysql_port=args.mysql_port,
            database_name=args.database_name,
            mysql_charset=args.mysql_charset,
            connect_timeout=args.connect_timeout
        )
        if not mysql_server.test_connection():
            logger.warning("数据库无法正常，请检查")
            sys.exit(1)
        args.mysql_server = mysql_server
        return args


def main(command_args):
    logger.info("处理开始。。。")
    args = CommandParser.parse_args(command_args)
    MySQLParser.parse_rdb(
        rdb_file_path=args.rdb_file_path,
        mysql_server=args.mysql_server,
        mysql_table_name=args.table_name,
        min_key_length=args.min_key_length,
        mysql_batch_insert_rows=args.mysql_batch_insert_rows,
        mysql_batch_sleep_seconds=args.mysql_batch_sleep_seconds
    )
    logger.info("处理完成。。。")


if __name__ == '__main__':
    LoggerHelper.init_logger(
        logger_name=CommonConfig.app_name,
        logger_level=logging.INFO,
        logger_dir=CommonConfig.app_log_dir
    )
    main(sys.argv[1:])
